package com.ruoyi.manage.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.constant.HttpStatus;
import com.ruoyi.common.constant.ManageRedisConstants;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.exception.CustomException;
import com.ruoyi.common.utils.CL253Api.MessageApi;
import com.ruoyi.common.utils.CLUtils;
import com.ruoyi.common.utils.DESUtil;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.VerifyCodeUtils;
import com.ruoyi.manage.baiduApi.impl.CardIdentificationClient;
import com.ruoyi.manage.baiduApi.impl.FaceThanClient;
import com.ruoyi.manage.baiduApi.request.CardRequest;
import com.ruoyi.manage.baiduApi.request.FaceRequest;
import com.ruoyi.manage.baiduApi.response.CardResponse;
import com.ruoyi.manage.baiduApi.response.FaceResponse;
import com.ruoyi.manage.domain.AppUser;
import com.ruoyi.manage.domain.UserTerms;
import com.ruoyi.manage.domain.request.FaceThanRequest;
import com.ruoyi.manage.domain.request.IdentityInformationRequest;
import com.ruoyi.manage.domain.request.VerificationCodeRequest;
import com.ruoyi.manage.mapper.AppUserMapper;
import com.ruoyi.manage.mapper.UserTermsMapper;
import com.ruoyi.manage.service.IAppAuthenticationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;
import sun.misc.BASE64Encoder;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @Author: wwy
 * @Date: 2021/3/3 15:04
 */
@Service
public class AppAuthenticationServiceImpl implements IAppAuthenticationService {
    @Autowired
    private RedisTemplate redisTemplate;
    /**
     * 人脸相似最小值
     */
    @Value("${faceSimilarityMinValue}")
    private Double faceSimilarityMinValue;
    /**
     * 数据加密密钥
     */
    @Value("${dataPassword}")
    private String dataPassword;
    /**
     * 短信验证码
     */
    @Value("${message.verificationCode}")
    private String verificationCode;
    @Autowired
    private AppUserMapper appUserMapper;
    @Autowired
    private UserTermsMapper userTermsMapper;

    /**
     * 获取身份信息
     * @param identityInformationRequest
     * @return
     */
    @Override
    public AjaxResult getIdentityInformation(IdentityInformationRequest identityInformationRequest) {
        if(identityInformationRequest == null || StringUtils.isEmpty(identityInformationRequest.getFilePath()) || StringUtils.isEmpty(identityInformationRequest.getIdCardSide())){
            throw new CustomException("参数错误", HttpStatus.BAD_REQUEST);
        }
        String filePath = identityInformationRequest.getFilePath().replace("/profile/upload","");
        //调用图文识别接口
        CardIdentificationClient cardIdentificationClient = new CardIdentificationClient();
        CardRequest cardRequest = new CardRequest();
        cardRequest.setImage(RuoYiConfig.getUploadPath()+filePath);
        cardRequest.setIdCardSide(identityInformationRequest.getIdCardSide());
        CardResponse cardResponse = cardIdentificationClient.identificationExecute(cardRequest);
        if(cardResponse.isSuccess()){
            return AjaxResult.success(cardResponse);
        }
        return AjaxResult.error("请重新上传");
    }

    /**
     * 人脸比对
     * @param faceThanRequest
     * @return
     */
    @Override
    public AjaxResult faceThan(FaceThanRequest faceThanRequest) {
        if(faceThanRequest == null || StringUtils.isEmpty(faceThanRequest.getImagePath1()) || StringUtils.isEmpty(faceThanRequest.getImagePath2())){
            throw new CustomException("参数错误", HttpStatus.BAD_REQUEST);
        }
        FaceThanClient faceThanClient = new FaceThanClient();
        FaceRequest faceRequest = new FaceRequest();
        String image1 = faceThanRequest.getImagePath1().replace("/profile/upload","");
        String image2 = faceThanRequest.getImagePath2().replace("/profile/upload","");
        String uploadPath = RuoYiConfig.getUploadPath();
        String image1Base64 = this.encodeBase64File(uploadPath + image1);
        String image2Base64 = this.encodeBase64File(uploadPath + image2);
        faceRequest.setImage1(image1Base64);
        faceRequest.setImage2(image2Base64);
        FaceResponse faceResponse = faceThanClient.faceThanExecute(faceRequest);
        if(faceResponse.isSuccess()){
            //成功
            int score = faceResponse.getScore();
            if(score >= faceSimilarityMinValue){
                //比对成功
                return AjaxResult.success("比对成功");
            }else{
                //比对失败
                return AjaxResult.error("比对失败");
            }
        }else{
            return AjaxResult.error("比对失败");
        }
    }

    @Override
    public AjaxResult saveInfo(AppUser appUser) {
        if(appUser == null || StringUtils.isEmpty(appUser.getAddress())
                || StringUtils.isEmpty(appUser.getName())
                || StringUtils.isEmpty(appUser.getIdentitynumber())
                || StringUtils.isEmpty(appUser.getPhone())
                || StringUtils.isEmpty(appUser.getOpenId())){
            throw new CustomException("参数错误", HttpStatus.BAD_REQUEST);
        }
        //判断用户是否已存在
        AppUser appUserParam = new AppUser();
        appUserParam.setOpenId(appUser.getOpenId());
        List<AppUser> appUsers = appUserMapper.selectAppUserList(appUserParam);

        if(appUsers.size()<=0){
            //不存在，进行新增
            //账号状态
            appUser.setStatus(1);
            appUser.setBindingStatus(1);
            String identitynumberEncrypt = DESUtil.encrypt(dataPassword, appUser.getIdentitynumber());
            String phoneEncrypt = DESUtil.encrypt(dataPassword, appUser.getPhone());
            appUser.setIdentitynumber(identitynumberEncrypt);
            appUser.setPhone(phoneEncrypt);
            appUserMapper.insertAppUser(appUser);
        }else{
            //存在进行修改
            AppUser appUser1 = appUsers.get(0);
            appUser.setBindingStatus(1);
            appUser.setOpenId(appUser1.getOpenId());
            appUser.setId(appUser1.getId());
            String identitynumberEncrypt = DESUtil.encrypt(dataPassword, appUser.getIdentitynumber());
            String phoneEncrypt = DESUtil.encrypt(dataPassword, appUser.getPhone());
            appUser.setIdentitynumber(identitynumberEncrypt);
            appUser.setPhone(phoneEncrypt);
            appUserMapper.updateAppUser(appUser);
        }
        String image1 = appUser.getImagePath1().replace("/profile/upload","");
        String image2 = appUser.getImagePath2().replace("/profile/upload","");
        String image3 = appUser.getImagePath3().replace("/profile/upload","");
        String uploadPath = RuoYiConfig.getUploadPath();
        //删除图片
        File file = new File(uploadPath + image1);
        if(file.exists()){
            file.delete();
        }
        File file1 = new File(uploadPath + image2);
        if(file1.exists()){
            file1.delete();
        }

        File file2 = new File(uploadPath + image3);
        if(file2.exists()){
            file2.delete();
        }
        return AjaxResult.success();
    }

    /**
     * 获取用户条款
     * @return
     */
    @Override
    public AjaxResult getUserTerms() {
        UserTerms userTerms = new UserTerms();
        List<UserTerms> userTerms1 = userTermsMapper.selectUserTermsList(userTerms);
        UserTerms userTerms2 = null;
        if(userTerms1.size()>=1){
            userTerms2 = userTerms1.get(0);
        }
        String content = userTerms2.getContent();
        content.replace("class=\"ql-align-center\">","");
        return AjaxResult.success(userTerms2);
    }

    /**
     * 获取手机验证码
     * @return
     * @param verificationCodeRequest
     */
    @Override
    public AjaxResult getPhoneVerification(VerificationCodeRequest verificationCodeRequest) {
        //验证码生成
        if(verificationCodeRequest == null || StringUtils.isEmpty(verificationCodeRequest.getPhone())){
            throw new CustomException("参数错误",HttpStatus.BAD_REQUEST);
        }
        String phone = verificationCodeRequest.getPhone();
        String code = VerifyCodeUtils.generateVerifyCode(6, "1234567890");
        ValueOperations valueOperations = redisTemplate.opsForValue();
        valueOperations.set(ManageRedisConstants.REGISTER_CODE + verificationCodeRequest.getPhone(),code,15, TimeUnit.MINUTES);

        MessageApi messageApi = CLUtils.getMessageApi();
        Map<String,String> optionMap = new HashMap<>();
        String message = verificationCode.replace("##code##", code);
        JSONObject jsonObject = messageApi.sendMessage(phone, message, optionMap);
        Map map = jsonObject.toJavaObject(Map.class);
        Object code1 = map.get("code");
        if(code1 != null){
            String codeStr = String.valueOf(code1);
            if("0".equals(codeStr)){
                return AjaxResult.success("验证码发送成功");
            }
        }
        throw new CustomException("验证码发送失败",HttpStatus.ERROR);
    }

    /**
     * 保存用户信息新版
     * @param appUser
     * @return
     */
    @Override
    public AjaxResult saveInfoNew(AppUser appUser) {
        if(appUser == null
                || StringUtils.isEmpty(appUser.getName())
                || StringUtils.isEmpty(appUser.getPhone())
                || StringUtils.isEmpty(appUser.getOpenId())
                || StringUtils.isEmpty(appUser.getCode())){
            throw new CustomException("参数错误", HttpStatus.BAD_REQUEST);
        }
        //获取验证码
        ValueOperations valueOperations = redisTemplate.opsForValue();
        Object verificationCodeCache = valueOperations.get(ManageRedisConstants.REGISTER_CODE + appUser.getPhone());
        if(verificationCodeCache != null){
            String verificationCodeCacheStr = String.valueOf(verificationCodeCache);
            if(!verificationCodeCacheStr.equals(appUser.getCode())){
                throw new CustomException("验证码错误",HttpStatus.ERROR);
            }
        }else{
            throw new CustomException("请重新获取验证码",HttpStatus.ERROR);
        }

        //判断用户是否已存在
        AppUser appUserParam = new AppUser();
        appUserParam.setOpenId(appUser.getOpenId());
        List<AppUser> appUsers = appUserMapper.selectAppUserList(appUserParam);

        if(appUsers.size()<=0){
            //不存在，进行新增
            //账号状态
            appUser.setStatus(1);
            appUser.setBindingStatus(1);
            String phoneEncrypt = DESUtil.encrypt(dataPassword, appUser.getPhone());
            appUser.setPhone(phoneEncrypt);
            appUserMapper.insertAppUser(appUser);
        }else{
            //存在进行修改
            AppUser appUser1 = appUsers.get(0);
            appUser.setBindingStatus(1);
            appUser.setOpenId(appUser1.getOpenId());
            appUser.setId(appUser1.getId());
            String phoneEncrypt = DESUtil.encrypt(dataPassword, appUser.getPhone());
            appUser.setPhone(phoneEncrypt);
            appUserMapper.updateAppUser(appUser);
        }
        return AjaxResult.success();
    }


    private String encodeBase64File(String path) {
        File file = new File(path);
        FileInputStream inputFile = null;
        try {
            inputFile = new FileInputStream(file);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        byte[] buffer = new byte[(int)file.length()];
        try {
            inputFile.read(buffer);
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            inputFile.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return new BASE64Encoder().encode(buffer);
    }
}
